package org.dromara.genealogy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.genealogy.domain.GeInfo;
import org.dromara.genealogy.domain.bo.GeInfoBo;
import org.dromara.genealogy.domain.bo.GeNameBo;
import org.dromara.genealogy.domain.vo.GeInfoVo;
import org.dromara.genealogy.domain.vo.GeNameTranVo;
import org.dromara.genealogy.domain.vo.GeNameVo;
import org.dromara.genealogy.service.IGeInfoService;
import org.dromara.genealogy.service.IGeNameService;
import org.dromara.utils.AsposeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.genealogy.domain.bo.GeGenealogyBo;
import org.dromara.genealogy.domain.vo.GeGenealogyVo;
import org.dromara.genealogy.domain.GeGenealogy;
import org.dromara.genealogy.mapper.GeGenealogyMapper;
import org.dromara.genealogy.service.IGeGenealogyService;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 族谱信息Service业务层处理
 *
 * @author qianjm
 * @date 2025-08-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class GeGenealogyServiceImpl implements IGeGenealogyService {

    private final GeGenealogyMapper baseMapper;

    private final IGeInfoService infoService;

    private final IGeNameService nameService;

    /**
     * 查询族谱信息
     *
     * @param id 主键
     * @return 族谱信息
     */
    @Override
    public GeGenealogyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询族谱信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 族谱信息分页列表
     */
    @Override
    public TableDataInfo<GeGenealogyVo> queryPageList(GeGenealogyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GeGenealogy> lqw = buildQueryWrapper(bo);
        Page<GeGenealogyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的族谱信息列表
     *
     * @param bo 查询条件
     * @return 族谱信息列表
     */
    @Override
    public List<GeGenealogyVo> queryList(GeGenealogyBo bo) {
        LambdaQueryWrapper<GeGenealogy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GeGenealogy> buildQueryWrapper(GeGenealogyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GeGenealogy> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(GeGenealogy::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), GeGenealogy::getCode, bo.getCode());
        lqw.like(StringUtils.isNotBlank(bo.getName()), GeGenealogy::getName, bo.getName());
        return lqw;
    }

    /**
     * 新增族谱信息
     *
     * @param bo 族谱信息
     * @return 是否新增成功
     */
    @Override
    public GeGenealogyBo insertByBo(GeGenealogyBo bo) {
        GeGenealogy add = MapstructUtils.convert(bo, GeGenealogy.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return bo;
    }

    /**
     * 修改族谱信息
     *
     * @param bo 族谱信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(GeGenealogyBo bo) {
        GeGenealogy update = MapstructUtils.convert(bo, GeGenealogy.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GeGenealogy entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除族谱信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 生成世系图word文档
     */
    @Override
    public void generateWord(Long geId) {

        //查询所有的族员数据
        GeNameBo nameBo = new GeNameBo();
        nameBo.setGeId(geId);
        List<GeNameTranVo> nameVos = nameService.queryListTran(nameBo);
        //遍历获取儿子数据
        List<GeNameTranVo> newNames = nameVos.stream().map(nameVo ->{
            nameVo.setChildrenList(nameVos.stream().filter(vo -> vo.getParentId().equals(nameVo.getId())).sorted(Comparator.comparing(GeNameTranVo::getRankNo)).toList());
            return nameVo;
        }).toList();
        //转化为linkList 将子节点插入到父节点之后
        //List<GeNameTranVo> linkNodes = new LinkedList<>(newNames);
        List<GeNameTranVo> newGnames = CollUtil.newArrayList();
        //遍历列表，将子节点插入到父节点之后
        if(CollUtil.isNotEmpty(newNames)){
            for (GeNameTranVo name : newNames) {
                GeNameTranVo node = BeanUtil.copyProperties(name, GeNameTranVo.class);
                List<GeNameTranVo> children = name.getChildrenList();
                if(CollUtil.isNotEmpty(children)){
                    GeNameTranVo firstChild = children.get(0);
                    node.setChildName(firstChild.getLastName());
                    node.setMark(firstChild.getMark());
                    newGnames.add(node);
                    if(children.size()>1){
                        for (int i = 1; i < children.size(); i++) {
                            GeNameTranVo child = children.get(i);
                            GeNameTranVo childNode = new GeNameTranVo();
                            childNode.setChildName(child.getLastName());
                            childNode.setGeneName(null);
                            childNode.setLastName("");
                            childNode.setMark(child.getMark());
                            childNode.setRankNo(child.getRankNo());
                            newGnames.add(childNode);
                        }
                    }
                }else{
                    newGnames.add(node);
                }
            }
        }

        for (GeNameTranVo name : newGnames) {
            System.out.println(name.getGeneName() + "& " + name.getLastName() + "& " +  name.getRankNo()+"&"+name.getChildName());
        }





        /*GeInfoBo bo = new GeInfoBo();
        bo.setInfoType("sxb");
        ArrayList<String> list = ListUtil.toList();
        List<GeInfoVo> infoVos =  infoService.queryList(bo);
        if(CollectionUtil.isNotEmpty(infoVos)){
            list.add(infoVos.get(0).getRemark());
            // 保存到文件（Java 11+）
            String savePath = "E:\\奥远科技\\项目文件\\族谱系统\\word\\测试生成文件\\" + System.currentTimeMillis() + ".docx";

            // 或者使用传统方式
            try (FileOutputStream fos = new FileOutputStream(savePath)) {
                AsposeUtils.convertHtmlStrToWord(list, fos);
                System.out.println("文档已保存至: " + savePath);
            } catch (IOException e) {
                System.out.println("文件保存失败");
            }
        }*/
    }
}
